<template>
  <section id="hero">
    <h1 class="tagline">
      <span class="accent">土逼浪波玩👉网络切换器</span>
    </h1>
    <div class="networkList">
      <el-row :gutter="20" style="width: 100%; padding: 0; margin: 0">
        <el-col :span="17" style="text-align: left">选择网卡：
          <el-select v-model="interfaceName" class="m-2" placeholder="Select" @change="showIp()">
            <el-option
                v-for="item in networkList"
                :key="item.ipAddress"
                :label="item.interfaceName"
                :value="item.interfaceName"
            />
          </el-select>
          <el-button :icon="Refresh" @click="refresh()" />
          <el-text class="mx-1" style="margin-left: 5px">当前网卡IP：{{interfaceIp}}</el-text>
        </el-col>
        <el-col :span="7" style="text-align: right; padding: 0">
          <el-button-group class="ml-4">
            <el-tooltip content="添加教室" placement="top" effect="light">
              <el-button type="primary" :icon="CirclePlus" @click="openAdd()" />
            </el-tooltip>
            <el-tooltip content="导入配置" placement="top" effect="light">
              <el-button type="primary" :icon="Upload" @click="importJson()" />
            </el-tooltip>
            <el-tooltip content="导出配置" placement="top" effect="light">
              <el-button type="primary" :icon="Download" @click="derivedJson()" />
            </el-tooltip>


            <el-popconfirm title="确定切换DHCP吗?" @confirm="setDhcp">
              <template #reference>
                  <el-button type="success" :icon="Platform" />
              </template>
            </el-popconfirm>


          </el-button-group>
        </el-col>
      </el-row>
    </div>

    <div class="description">
      <el-table v-loading="isLoading"
                :data="ipListData"
                :default-sort="{ prop: 'classRoom', order: 'descending' }" border
                style="width: 100%; height: calc(100vh - 170px)"
                class="tb-edit"
                :cell-style="{ textAlign: 'center' }"
                highlight-current-row
                @row-click="handleCurrentChange"
                :row-class-name="tableRowClassName">
        <el-table-column fixed prop="classRoom" sortable label="教室" width="80" />
        <el-table-column prop="ipAddress" label="IP" width="140">
          <template #default="scope">
            <el-input size="small" v-model="scope.row.ipAddress" placeholder="请输入内容"
                      @change="handleEdit(scope.$index, scope.row)"></el-input> <span>{{scope.row.ipAddress}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="gateway" label="网关" width="140">
          <template #default="scope">
            <el-input size="small" v-model="scope.row.gateway" placeholder="请输入内容"
                      @change="handleEdit(scope.$index, scope.row)"></el-input> <span>{{scope.row.gateway}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="DNSA" label="首选DNS" width="140">
          <template #default="scope">
            <el-input size="small" v-model="scope.row.DNSA" placeholder="请输入内容"
                      @change="handleEdit(scope.$index, scope.row)"></el-input> <span>{{scope.row.DNSA}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="DNSB" label="备选DNS" width="140">
          <template #default="scope">
            <el-input size="small" v-model="scope.row.DNSB" placeholder="请输入内容"
                      @change="handleEdit(scope.$index, scope.row)"></el-input> <span>{{scope.row.DNSB}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-popconfirm title="确定切换吗?" @confirm="setIp(scope.row.classRoom)">
              <template #reference>
                  <el-button type="primary" size="small" :icon="Promotion"></el-button>
              </template>
            </el-popconfirm>
            <el-popconfirm title="确定要删除?" @confirm="handleDelete(scope.$index, scope.row)">
              <template #reference>
                  <el-button
                      size="small"
                      type="danger"
                      :icon="Delete"
                  />
              </template>
            </el-popconfirm>

          </template>
        </el-table-column>
      </el-table>
    </div>

  </section>

  <footer>
    <div class="left">{{bottomText}}</div>
    <div class="right">by Sniper</div>
  </footer>

  <el-dialog
      title="添加教室"
      width="300"
      v-model="dialogVisible"
      :close-on-click-modal="false">
    <el-form
        ref="form"
        label-position="right"
        label-width="100px"
        style="max-width: 460px"
        :model="fromData"
        :rules="rules"
    >
      <el-form-item label="教室" prop="classRoom">
        <el-input v-model="fromData.classRoom" />
      </el-form-item>
      <el-form-item label="IP" prop="ipAddress">
        <el-input v-model="fromData.ipAddress" />
      </el-form-item>
      <el-form-item label="网关" prop="gateway">
        <el-input v-model="fromData.gateway" />
      </el-form-item>
      <el-form-item label="首选DNS" prop="DNSA">
        <el-input v-model="fromData.DNSA" />
      </el-form-item>
      <el-form-item label="备选DNS">
        <el-input v-model="fromData.DNSB" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click.native="dialogVisible = false">取消</el-button>
      <el-button type="primary" :loading="addLoading" @click="handleAdd('form')">提交</el-button>
    </div>
  </el-dialog>
</template>
<script>


import { ipcApiRoute } from '@/api/main';
import {ipc} from "@/utils/ipcRenderer";
import {
  CirclePlus,
  Delete,
  Expand,
  Download,
  Refresh,
  RefreshRight,
  Upload,
  Platform,
  Promotion
} from "@element-plus/icons-vue";
import {ElMessage, ElLoading} from "element-plus";
export default {
  computed: {
    Promotion() {
      return Promotion
    },
    Platform() {
      return Platform
    },
    Upload() {
      return Upload
    },
    Download() {
      return Download
    },
    Expand() {
      return Expand
    },
    RefreshRight() {
      return RefreshRight
    },
    CirclePlus() {
      return CirclePlus
    },
    Delete() {
      return Delete
    },
    Refresh() {
      return Refresh
    }
  },
  data() {
    return {
      bottomText:'当前版本：',
      interfaceName: '请选择网卡',
      interfaceIp:'',
      isLoading: false,
      networkList:[],
      ipListData: [],
      dialogVisible:false,//模态框是否显示
      addLoading: false,       //是否显示loading
      fromData:{
        classRoom:'',
        ipAddress:'',
        gateway:'',
        DNSA:'10.10.10.10',
        DNSB:'114.114.114.114'
      },
      isDark: null,
      rules:{
        classRoom: [
          {required: true,message: "教室必须填写",trigger: "blur"}
        ],
        ipAddress: [
          { required: true, message: 'IP必须填写', trigger: 'blur' }
        ],
        gateway: [
          { required: true, message: '网关必须填写', trigger: 'blur' }
        ],
        DNSA: [
          { required: true, message: '主DNS必须填写', trigger: 'blur' }
        ]
      }
    };
  },
  mounted() {
    this.loadNetworkList();
    this.loadIpList();
    this.getVersion();
  },
  methods: {

    /**
     * 获取应用版本号
     */
    getVersion(){
      ipc.invoke(ipcApiRoute.getVersion, {}).then(res=>{
        console.log(res)
        this.bottomText = "当前版本："+res
      })
    },

    /**
     * 导入配置
     */
    importJson(){
      this.isLoading = true;
      ipc.invoke(ipcApiRoute.selectJson, {}).then(res=>{
        console.log(res)
        this.isLoading = false;
        if (res){
          this.loadIpList();
          ElMessage.success("数据导入成功！");
        }else{
          ElMessage.error("数据导入失败！");
        }
      })
    },
    /**
     * 导出配置
     */
    derivedJson(){
      this.isLoading = true;
      ipc.invoke(ipcApiRoute.saveJson, {}).then(res=>{
        console.log(res)
        this.isLoading = false;
        if (res){
          ElMessage.success("数据导出成功！");
        }else {
          ElMessage.error("数据导出失败！");
        }
      })
    },
    /**
     * 刷新按钮
     */
    refresh(){
      this.loadNetworkList();
      this.loadIpList();
    },
    /**
     * 添加窗口模态窗
     */
    openAdd(){
      this.dialogVisible = true
    },
    /**
     * 数据列点击事件
     * @param row
     * @param event
     * @param column
     */
    handleCurrentChange(row, event, column) {
      //console.log(row, event, column, event.currentTarget)
     // console.log("根据 Element Table @row-click=handleCurrentChange 事件，当该行点击的时候会动态添加一个 .current-row 的class属性，然后在 css 中进行 display 控制就行了。")
    },
    /**
     * 表格切换事件
     * @param row
     * @param rowIndex
     * @returns {string}
     */
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex;
      if ((rowIndex + 1) % 2 === 1) {
        return 'warning-row';
      } else {
        return 'success-row';
      }
    },
    /**
     * 编辑字段
     * @param index
     * @param row
     */
    handleEdit(index, row){

      this.isLoading = true;
      const params = {
        action: 'update',
        update_name: {
          classRoom: row.classRoom,
        },
        update_arr: {
          ipAddress:row.ipAddress,
          gateway:row.gateway,
          DNSA:row.DNSA,
          DNSB:row.DNSB,
        }
      }
      ipc.invoke(ipcApiRoute.jsondbOperation, params).then(res=>{
        this.ipListData = res.all_list;
        this.isLoading = false;
      })
    },
    /**
     * 删除数据
     * @param index
     * @param row
     */
    handleDelete(index, row){
      this.isLoading = true;
      const params = {
        action: 'del',
        delete_name: {
          classRoom: row.classRoom,
        }
      }
      ipc.invoke(ipcApiRoute.jsondbOperation, params).then(res=>{
        this.isLoading = false;
        this.ipListData = res.all_list;
        ElMessage.success("删除教室成功！");
      })
    },
    /**
     * 添加数据
     * @param form
     */
    handleAdd(form){
      this.$refs[form].validate(valid => {
        if (valid) {

          const params = {
            action: 'get',
            search_age: {
              classRoom: this.fromData.classRoom
            }
          }
          ipc.invoke(ipcApiRoute.jsondbOperation, params).then(res=>{
            if (res.result.length === 0) {
              this.isLoading = true;
              const params2 = {
                action: 'add',
                info: {
                  classRoom: this.fromData.classRoom,
                  ipAddress:this.fromData.ipAddress,
                  gateway:this.fromData.gateway,
                  DNSA:this.fromData.DNSA,
                  DNSB:this.fromData.DNSB,
                }
              }
              ipc.invoke(ipcApiRoute.jsondbOperation, params2).then(res=>{
                this.isLoading = false;
                this.ipListData = res.all_list;
                ElMessage.success("教室添加成功！");
                this.dialogVisible = false
              })

            }else{
              ElMessage.error("该教室已存在了！");
            }
          })
        }
      });
    },
    /**
     * 加载网卡
     */
    loadNetworkList () {
      this.networkList = [];
      this.interfaceName = '请选择网卡';
      this.interfaceIp = '';
      ipc.invoke(ipcApiRoute.getAllNetwork, '').then(res=>{
        this.networkList = res
      })
    },
    /**
     * 加载数据库
     */
    loadIpList () {
      this.isLoading = true;
      const params = {
        action: 'all',
      }
      ipc.invoke(ipcApiRoute.jsondbOperation, params).then(res=>{
        this.isLoading = false;
        this.ipListData = res.all_list;
      })
    },
    /**
     * 显示网卡IP
     */
    showIp () {
      ipc.invoke(ipcApiRoute.getIp, this.interfaceName).then(res=>{
        this.interfaceIp = res;
      });
    },
    /**
     * 设置IP
     * @param classRoom
     */
    setIp (classRoom) {
      if (this.interfaceName === ''){
        ElMessage.error("请选择网卡后再设置IP");
        return;
      }
      this.isLoading = true;
      this.bottomText = '正在将当前网卡IP设置为：'+ classRoom + '教室IP，请稍等...';
      const params = {
        interfaceName: this.interfaceName,
        classRoom: classRoom
      }
      ipc.invoke(ipcApiRoute.setIPAddress, params).then(res=>{
        this.isLoading = false;
        if (res){
          this.bottomText = '成功设置IP为：'+ classRoom + '教室IP';
        }else{
          this.bottomText = '设置失败！请重新以管理员身份运行本软件';
        }

      });
    },
    /**
     * 设置自动IP
     */
    setDhcp(){
      if (this.interfaceName === ''){
        ElMessage.error("请选择网卡后再设置IP");
        return;
      }
      this.isLoading = true;
      this.bottomText = '正在将当前网卡IP设置为：DHCP，请稍等...';
      const params = {
        interfaceName: this.interfaceName
      }
      ipc.invoke(ipcApiRoute.setIPDhcp, params).then(res=>{
        this.isLoading = false;
        if (res){
          this.bottomText = '成功设置IP为：DHCP';
        }else{
          this.bottomText = '设置失败！请重新以管理员身份运行本软件';
        }
      });
    }


  }
};
</script>
<style scoped>

footer {
  width: 100%;
  height: 30px;
  line-height: 30px;
  font-size: 14px;
  background-color: #b1b6b6;
  position: fixed;
  z-index: 999;
  bottom: 0;
  left: 0;
}

footer .left{
  width: 100vh;
  float: left;
  text-align: left;
  padding-left: 5px;
}

footer .right{
  border-left: 1px solid #dedede;
  width: 30vh;
  float: right;
  text-align: center;
}

#hero {
  padding: 10px 5px 0 5px;
  text-align: center;
}

.tagline {
  font-size: 32px;
  line-height: 1.25;
  font-weight: bold;
  letter-spacing: -1.5px;
  margin: 0px auto;
  margin-bottom: 20px;
}

html:not(.dark) .accent,
.dark .tagline {
  background: -webkit-linear-gradient(315deg, #42d392 25%, #647eff);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
.networkList{
  font-size: 14px;
  line-height: 50px;
  height: 50px;
}
.tb-edit .el-input {
  display: none
}

.tb-edit .current-row .el-input {
  display: block
}

.tb-edit .current-row .el-input+span {
  display: none
}

</style>
  